package com.example.demo.test;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class Request {
    //    cookie的传统获取
    @RequestMapping("/getCookies")
    public String getCookie(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();

//        lambda表达式
        if(cookies != null) {
            Arrays.stream(cookies).forEach(x -> System.out.println(x.getName()+":"+x.getValue()));
            return "获取Cookie成功！";
        }
        return "Cookie为空";
    }

    @RequestMapping("/getCookies1")
    public String getCookie1(@CookieValue("hi") String hi) {
        return "hi:"+hi;
    }
//只能获取到某一些cookie 因为 只设定了一个 hi

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("username","zhang");
        return "设置session成功";
    }

    @RequestMapping("/getSession1")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        return "名称："+username;
    }

    @RequestMapping("/getSession2")
    public String getSession(HttpSession session) {;
        String username = (String)session.getAttribute("username");
        return "名称："+username;
    }

    @RequestMapping("/getSession3")
    public String getSession(@SessionAttribute(value = "username",required = false) String username) {;
        return "名称："+username;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "userAgent"+userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent"+userAgent;
    }

}
